package com.xl.studentpass.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xl.studentpass.entity.ImageInfoEntity;
import com.xl.studentpass.mapper.ImageMapper;
import com.xl.studentpass.service.ImageUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author: xl
 * @createTime: 2023/5/25 16:28:19
 * @program: student-pass
 * @e-mail: 2199396150@qq.com
 * @description:
 */
@Service
@Slf4j
public class ImageUploadServiceImpl extends ServiceImpl<ImageMapper, ImageInfoEntity> implements ImageUploadService {
    @Value("${file.upload.path}")
    private String uploadPath;

    @Override
    public List<Integer> uploadImage(String type, MultipartFile[] imgFiles, HttpServletRequest request, Integer userId) {
        if (imgFiles.length < 1) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(uploadPath).append(File.separator).append(type).append(File.separator);
        try {

            ArrayList<Integer> urlIds = new ArrayList<>();

            for (MultipartFile imgFile : imgFiles) {
                String shuffleName = UUID.randomUUID().toString().substring(1, 18).replace("-", "");
                sb.append(shuffleName).append(".jpg");
                File file = new File(sb.toString());
                if (!file.exists()) {
                    boolean flag = file.mkdirs();
                    if (flag) {
                        imgFile.transferTo(file);
                        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + type + "/" + shuffleName + ".jpg";
                        ImageInfoEntity imageInfo = new ImageInfoEntity();
                        imageInfo.setImageUrl(url);
                        imageInfo.setUserId(userId);
                        imageInfo.setValid(0);
                        this.saveOrUpdate(imageInfo);
                        urlIds.add(imageInfo.getId());
                        log.info(sb + "文件保存成功");
                        int index = sb.indexOf(shuffleName);
                        sb.delete(index, sb.length());
                    }
                }
            }
            return urlIds;
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
    }

    @Override
    public List<Integer> uploadImage(String type, MultipartFile[] imgFile, HttpServletRequest request) {
        return uploadImage(type, imgFile, request, null);
    }
}
